Popular Searches
Popular Course Categories
Popular Courses

Working with String Methods and Formatting

Working with String Methods and Formatting

Python Data Structures — Strings, Lists, and Tuples

Working with String Methods and Formatting in Python

Course: Python Training

Topic: Working with String Methods and Formatting

Course Link: Python Training Course

Demo Registration: Register for a Free Course Demo

Website: JustAcademy


1. Introduction to Strings in Python

A string is a sequence of characters used to represent text in Python. Strings can contain letters, numbers, spaces, punctuation marks, and special characters. They are commonly used for names, addresses, messages, user input, file paths, and formatted reports.

Strings can be created using single quotes, double quotes, or triple quotes.

name = 'Rahul'
city = "Mumbai"
message = """Welcome to Python programming."""

print(name)
print(city)
print(message)

Output:

Rahul
Mumbai
Welcome to Python programming.

Python provides many built-in string methods that help developers search, modify, validate, split, join, and format text without writing complex logic manually.

2. Important Characteristics of Strings

  • Ordered: Characters appear in a specific sequence and can be accessed by index.
  • Immutable: Individual characters cannot be changed directly after a string is created.
  • Iterable: A string can be processed one character at a time using a loop.
  • Unicode support: Strings can contain characters from many languages and writing systems.
  • Rich built-in methods: Python includes methods for case conversion, trimming, searching, splitting, and validation.
text = "Python"
print(text[0])
print(text[-1])
print(len(text))

# Strings are immutable.
# text[0] = "J"  # Raises TypeError

Output:

P
n
6

3. Understanding String Methods

A string method is a built-in operation called on a string using dot notation. Most string methods return a new string or another result instead of modifying the original string.

text = "python programming"
result = text.upper()

print(result)
print(text)

Output:

PYTHON PROGRAMMING
python programming

In this example, upper() returns an uppercase version of the text, while the original variable remains unchanged.

4. Case Conversion Methods

Case conversion methods are useful for displaying text consistently, normalizing user input, and preparing text for comparison.

Method Purpose Example Result
upper() Converts letters to uppercase. "python".upper() → "PYTHON"
lower() Converts letters to lowercase. "PYTHON".lower() → "python"
capitalize() Capitalizes the first character and lowercases the remaining characters. "hello WORLD".capitalize() → "Hello world"
title() Capitalizes the beginning of words according to Python's title-casing rules. "python basics".title() → "Python Basics"
swapcase() Changes lowercase letters to uppercase and vice versa. "PyThOn".swapcase() → "pYtHoN"
casefold() Performs stronger lowercasing for caseless text comparison. "HELLO".casefold() → "hello"

Example: Case Conversion

text = "welcome to PYTHON programming"

print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())
print(text.swapcase())
print("Straße".casefold())

Output:

WELCOME TO PYTHON PROGRAMMING
welcome to python programming
Welcome to python programming
Welcome To Python Programming
WELCOME TO python PROGRAMMING
strasse

When to Use Case Conversion

  • Use lower() or casefold() when comparing text without case differences.
  • Use upper() for headings, labels, or codes that should appear in uppercase.
  • Use title() for simple title-style display, but do not assume it handles every name or language convention correctly.
  • Use capitalize() when a sentence or label should begin with a capital letter.

5. Removing Unwanted Spaces and Characters

User input and imported text may contain unwanted spaces or specific characters at the beginning or end. Python provides three useful methods for cleaning these values.

Method Description
strip() Removes matching whitespace or specified characters from both ends.
lstrip() Removes matching whitespace or specified characters from the left side.
rstrip() Removes matching whitespace or specified characters from the right side.
text = "   Learn Python   "

print(text.strip())
print(text.lstrip())
print(text.rstrip())

code = "###PYTHON###"
print(code.strip("#"))

Output:

Learn Python
Learn Python   
   Learn Python
PYTHON

Important: The argument to strip(), lstrip(), or rstrip() is treated as a collection of characters, not as one exact substring.

text = "xyPythonxy"
print(text.strip("xy"))

Output:

Python

For removing an exact prefix or suffix, use removeprefix() and removesuffix().

filename = "report.csv"
url = "https://example.com"

print(filename.removesuffix(".csv"))
print(url.removeprefix("https://"))

Output:

report
example.com

6. Searching Within Strings

Python offers methods to find text and determine whether a string contains a particular sequence of characters.

Method Purpose Result
find() Returns the first matching position, or -1 if not found. Integer
rfind() Returns the last matching position, or -1 if not found. Integer
index() Returns the first matching position; raises ValueError if not found. Integer or exception
rindex() Returns the last matching position; raises ValueError if not found. Integer or exception
count() Counts non-overlapping occurrences of a substring. Integer
text = "Python is easy, and Python is powerful."

print(text.find("Python"))
print(text.rfind("Python"))
print(text.index("easy"))
print(text.count("Python"))
print(text.find("Java"))

Output:

0
18
10
2
-1

Using Start and End Positions

Methods such as find(), rfind(), index(), and count() can accept optional start and end positions to limit the area being examined.

text = "one two one two"

print(text.find("one", 1))
print(text.count("two", 0, 7))

Output:

8
1

7. Checking the Beginning and End of Strings

Use startswith() and endswith() to check whether text begins or ends with a particular value.

filename = "report.pdf"
website = "https://example.com"

print(filename.endswith(".pdf"))
print(filename.startswith("report"))
print(website.startswith("https://"))
print(filename.endswith(".csv"))

Output:

True
True
True
False

These methods are useful for basic filename checks, prefix validation, and text classification. They do not replace security checks or complete validation of file types and URLs.

8. Replacing Text

The replace() method returns a new string in which occurrences of a specified substring are replaced with another value.

Syntax:

string.replace(old, new, count)
  • old: The text to search for.
  • new: The replacement text.
  • count: Optional maximum number of replacements.
message = "I like Java. Java is popular."

print(message.replace("Java", "Python"))
print(message.replace("Java", "Python", 1))

Output:

I like Python. Python is popular.
I like Python. Java is popular.

Because strings are immutable, the original string remains unchanged unless the returned value is assigned to a variable.

9. Splitting Strings into Lists

The split() method divides a string into a list of substrings. It is useful for processing comma-separated values, words, and simple text records.

sentence = "Python is easy to learn"
words = sentence.split()

print(words)

data = "Amit,25,Mumbai"
records = data.split(",")

print(records)

Output:

['Python', 'is', 'easy', 'to', 'learn']
['Amit', '25', 'Mumbai']

Limiting the Number of Splits

text = "red-green-blue-yellow"

print(text.split("-", 2))

Output:

['red', 'green', 'blue-yellow']

Using splitlines()

The splitlines() method splits text at line boundaries.

text = """First line
Second line
Third line"""

print(text.splitlines())

Output:

['First line', 'Second line', 'Third line']

Best practice: Do not parse complex CSV files using only split(","). Real CSV data can contain quoted commas, embedded newlines, and escaped quotes. Use Python's csv module for proper CSV processing.

10. Joining Strings

The join() method combines strings from an iterable using a separator. It is often more convenient and efficient than repeatedly concatenating strings inside a loop.

words = ["Learn", "Python", "Today"]

print(" ".join(words))
print("-".join(words))
print(", ".join(words))

Output:

Learn Python Today
Learn-Python-Today
Learn, Python, Today

The separator is written before join(). Every item in the iterable must be a string.

values = ["Age", "25", "City", "Mumbai"]
result = " | ".join(values)
print(result)

Output:

Age | 25 | City | Mumbai

If a list contains numbers, convert them to strings before joining:

numbers = [10, 20, 30]
result = ", ".join(str(number) for number in numbers)
print(result)

Output:

10, 20, 30

11. Testing String Content

String testing methods return Boolean values. They help validate the general type of text a user has entered.

Method Returns True when...
isalpha() All characters are alphabetic and the string is not empty.
isdigit() All characters are digits recognized by Unicode's digit classification.
isdecimal() All characters are decimal characters, such as ordinary decimal digits.
isnumeric() All characters are numeric characters according to Unicode.
isalnum() All characters are alphabetic or numeric and the string is not empty.
isspace() All characters are whitespace and the string is not empty.
islower() There is at least one cased character and all cased characters are lowercase.
isupper() There is at least one cased character and all cased characters are uppercase.
istitle() The string follows Python's title-case rules.
isascii() All characters are ASCII characters, including an empty string.
print("Python".isalpha())
print("12345".isdigit())
print("123.45".isdigit())
print("Python123".isalnum())
print("   ".isspace())
print("HELLO".isupper())
print("hello".islower())
print("".isascii())

Output:

True
True
False
True
True
True
True
True

Important distinction: These methods are useful for basic character checks, but they are not complete validation rules for email addresses, phone numbers, usernames, passwords, or financial values. Real applications should define validation rules appropriate to their requirements.

12. Padding, Alignment, and Zero-Filling

Python provides methods to make strings a specified width. These are useful for console reports, simple tables, identifiers, and formatted output.

Method Purpose
center(width, fillchar) Centers the text within the specified width.
ljust(width, fillchar) Left-aligns the text by adding padding on the right.
rjust(width, fillchar) Right-aligns the text by adding padding on the left.
zfill(width) Adds zero characters on the left until the requested width is reached.
text = "Python"

print(text.center(12, "-"))
print(text.ljust(10, "."))
print(text.rjust(10, "."))
print("42".zfill(5))

Output:

---Python---
Python....
....Python
00042

When the specified width is shorter than or equal to the original string length, these methods return the string without shortening it. The fill character for center(), ljust(), and rjust() must be a single character.

13. String Formatting: An Overview

String formatting inserts variable values into a text template. It is commonly used to create personalized messages, invoices, reports, logs, summaries, and user-friendly output.

Python supports several approaches:

  • String concatenation using the + operator.
  • Formatted string literals, commonly called f-strings.
  • The str.format() method.
  • Percent-style formatting using %, which is an older technique still found in existing code.

14. Formatting with String Concatenation

Concatenation combines strings using the + operator. Non-string values must generally be converted before they can be concatenated with strings.

name = "Priya"
age = 24

message = "My name is " + name + " and I am " + str(age) + " years old."
print(message)

Output:

My name is Priya and I am 24 years old.

This approach is acceptable for simple cases, but long expressions become difficult to read. F-strings or str.format() are usually clearer for messages containing several values.

15. Formatting with f-Strings

F-strings are a modern, readable way to insert expressions into strings. They were introduced in Python 3.6. Add the letter f or F before the opening quote, then place expressions inside curly braces.

name = "Aarav"
age = 22
city = "Pune"

message = f"My name is {name}, I am {age} years old, and I live in {city}."
print(message)

Output:

My name is Aarav, I am 22 years old, and I live in Pune.

Using Expressions Inside f-Strings

F-strings can evaluate expressions, call functions, and perform calculations.

a = 15
b = 5

print(f"Sum: {a + b}")
print(f"Product: {a * b}")
print(f"Uppercase: {"python".upper()}")

The last example above uses nested quotation marks and is supported by modern Python versions that allow reusing quote types inside f-strings. For broader compatibility with older Python versions, write it as follows:

word = "python"
print(f"Uppercase: {word.upper()}")

Output:

Uppercase: PYTHON

Formatting Numbers to Decimal Places

Use a format specification such as :.2f to display a floating-point number with two digits after the decimal point.

price = 1250.5678

print(f"Price: {price:.2f}")
print(f"Price: {price:.3f}")

Output:

Price: 1250.57
Price: 1250.568

Formatting controls how a value is displayed; it does not necessarily change the original variable's numeric value.

Formatting Percentages

completion = 0.875
print(f"Completion: {completion:.1%}")

Output:

Completion: 87.5%

Formatting Large Numbers with Separators

population = 1250000
amount = 9876543.21

print(f"Population: {population:,}")
print(f"Amount: {amount:,.2f}")

Output:

Population: 1,250,000
Amount: 9,876,543.21

Aligning Values with f-Strings

name = "Riya"
score = 92

print(f"|{name:<12}|")
print(f"|{name:>12}|")
print(f"|{name:^12}|")
print(f"Score: {score:05d}")

Output:

|Riya        |
|        Riya|
|    Riya    |
Score: 00092
  • < aligns text to the left.
  • > aligns text to the right.
  • ^ centers text.
  • 05d formats an integer with a minimum width of five characters, using zeros as padding.

16. Formatting with the str.format() Method

The format() method inserts values into placeholders marked by curly braces. It is useful in code that uses a reusable template or requires compatibility with Python versions before f-strings were introduced.

name = "Karan"
age = 28

message = "My name is {} and I am {} years old.".format(name, age)
print(message)

Output:

My name is Karan and I am 28 years old.

Using Positional Placeholders

template = "{0} scored {1} marks. {0} passed the exam."
print(template.format("Anaya", 95))

Output:

Anaya scored 95 marks. Anaya passed the exam.

Using Named Placeholders

message = "Name: {name}, Department: {department}".format(
    name="Rohit",
    department="IT"
)

print(message)

Output:

Name: Rohit, Department: IT

Number Formatting with format()

price = 799.999
print("Price: {:.2f}".format(price))

amount = 2500000
print("Amount: {:,}".format(amount))

Output:

Price: 800.00
Amount: 2,500,000

17. Percent-Style Formatting

Percent-style formatting is an older technique used in legacy Python programs. It uses conversion markers such as %s, %d, and %f.

Specifier Purpose
%s Converts a value to its string representation.
%d Formats an integer.
%f Formats a floating-point number.
%.2f Displays a floating-point value with two decimal places.
name = "Meera"
age = 26
salary = 45678.456

print("Name: %s" % name)
print("Age: %d" % age)
print("Salary: %.2f" % salary)
print("%s is %d years old." % (name, age))

Output:

Name: Meera
Age: 26
Salary: 45678.46
Meera is 26 years old.

For new code, prefer f-strings or str.format() when they make the expression clearer. Percent-style formatting remains useful when maintaining existing programs.

18. Advanced Format Specifications

F-strings and str.format() support a shared format specification syntax. It can control alignment, width, fill characters, signs, precision, and number representation.

Format Meaning Example
{value:.2f} Two decimal places. 12.35
{value:8.2f} Width of at least eight characters and two decimal places. 12.35
{value:+d} Show the sign for positive and negative integers. +12
{value:,} Use commas as thousands separators. 1,000,000
{value:b} Display an integer in binary. 1010
{value:x} Display an integer in lowercase hexadecimal. ff
{value:e} Display a number in scientific notation. 1.230000e+04
number = 255
value = 12345.678

print(f"Binary: {number:b}")
print(f"Hexadecimal: {number:x}")
print(f"Scientific: {value:.2e}")
print(f"Rounded display: {value:.1f}")

Output:

Binary: 11111111
Hexadecimal: ff
Scientific: 1.23e+04
Rounded display: 12345.7

19. Formatting Dates and Times

For date and time output, Python's datetime objects support the strftime() method. It formats date and time values using directives.

from datetime import datetime

now = datetime(2026, 10, 22, 10, 30)

print(now.strftime("%d-%m-%Y"))
print(now.strftime("%B %d, %Y"))
print(now.strftime("%H:%M"))

Output:

22-10-2026
October 22, 2026
10:30
Directive Meaning
%d Day of the month as two digits.
%m Month as two digits.
%Y Four-digit year.
%B Full month name.
%A Full weekday name.
%H Hour in 24-hour format.
%M Minute.
%S Second.

For international applications, remember that displayed dates may depend on locale conventions and timezone requirements. Store and process date-time values carefully when applications work across time zones.

20. Escape Characters and Special Formatting

Escape sequences represent characters that are difficult to type directly or have special meaning in strings.

Escape Sequence Meaning
\n New line.
\t Horizontal tab.
\\ Backslash character.
\' Single quote.
\" Double quote.
text = "Name:\tAmit\nCourse:\tPython"
print(text)

path = "C:\\Users\\Student\\Documents"
print(path)

Output:

Name:   Amit
Course: Python
C:\Users\Student\Documents

Raw strings, written with an r prefix, are useful for regular expressions and Windows-style paths because backslashes are generally treated literally.

path = r"C:\Users\Student\Documents"
print(path)

Output:

C:\Users\Student\Documents

21. Practical Example: Student Result Report

This example combines string methods, whitespace cleanup, case conversion, numeric conversion, and f-string formatting to generate a simple student report.

student_name = "  riya sharma  "
course = "python programming"
marks = 87.456

# Clean the input text.
student_name = student_name.strip().title()
course = course.strip().title()

# Format the report.
print("=" * 35)
print(f"Student Name : {student_name}")
print(f"Course       : {course}")
print(f"Marks        : {marks:.2f}")
print("=" * 35)

Output:

===================================
Student Name : Riya Sharma
Course       : Python Programming
Marks        : 87.46
===================================

This approach makes the report readable and consistent. In production applications, student names and course titles may require more specialized capitalization rules than title() provides.

22. Practical Example: Cleaning and Formatting User Input

Suppose a program receives a person's name and email address. The input may contain extra spaces or inconsistent letter casing.

name_input = "  AMIT KUMAR "
email_input = "  [email protected]  "

name = name_input.strip().title()
email = email_input.strip().lower()

print(f"Name: {name}")
print(f"Email: {email}")

Output:

Name: Amit Kumar
Email: [email protected]

Lowercasing an email address is a common normalization choice for many applications, but technically the local part of an email address can have case-sensitive behavior under standards. Follow the rules of the system that stores or verifies the address rather than assuming every address can always be changed safely.

23. Common String Method and Formatting Errors

Error or Problem Cause Solution
Calling a method without parentheses Writing text.upper instead of text.upper(). Call the method using parentheses.
Expecting the original string to change String methods return a result rather than modifying the existing string. Assign the result to a variable when needed.
Concatenating text and an integer The + operator cannot directly concatenate a string and an integer. Use str() or an f-string.
Using index() for a missing value index() raises ValueError if no match exists. Use find() when a missing result should return -1.
Joining numbers directly join() expects strings. Convert values to strings first.
Incorrect placeholder count The formatting template and provided values do not match. Check positional and named placeholders.
Unexpected decimal output A format specifier may round the displayed value. Choose suitable precision and retain the original numeric value for calculations.
Using strip() to remove an exact word strip() removes any matching characters from the ends. Use removeprefix() or removesuffix() for exact prefix or suffix removal.

Error Example: String and Integer Concatenation

age = 25

# This raises TypeError:
# message = "Age: " + age

# Correct approach 1:
message = "Age: " + str(age)

# Correct approach 2:
message = f"Age: {age}"

print(message)

Output:

Age: 25

24. Best Practices for Working with Strings

  • Use descriptive variable names such as full_name, email_address, and formatted_price.
  • Prefer f-strings for readable messages containing variables and simple expressions.
  • Use strip() to remove unwanted surrounding whitespace from input when appropriate.
  • Use lower() or casefold() for case-insensitive comparisons according to the data's requirements.
  • Remember that string methods do not mutate the original string.
  • Use join() when combining multiple string values.
  • Use find() when the absence of a match is an expected outcome.
  • Use the csv module for CSV files and dedicated validation logic for structured data.
  • Do not treat simple string checks as complete security validation.
  • Keep calculations separate from display formatting, especially for prices and other numeric values.
  • Never build SQL queries by directly inserting untrusted input into strings. Use parameterized queries instead.
  • Be careful when formatting personal names, international text, currencies, and dates because conventions can vary.

25. Mini Project: Product Invoice Generator

Project objective: Build a small invoice generator that cleans customer information and formats product prices, quantities, and totals.

Program

customer_name = "  neha patil "
product_name = "  wireless keyboard "
price = 1499.5
quantity = 2

# Clean text values.
customer_name = customer_name.strip().title()
product_name = product_name.strip().title()

# Calculate the total.
total = price * quantity

# Display the invoice.
print("=" * 40)
print("             PRODUCT INVOICE")
print("=" * 40)
print(f"Customer : {customer_name}")
print(f"Product  : {product_name}")
print(f"Price    : ₹{price:,.2f}")
print(f"Quantity : {quantity}")
print("-" * 40)
print(f"Total    : ₹{total:,.2f}")
print("=" * 40)

Sample Output:

========================================
             PRODUCT INVOICE
========================================
Customer : Neha Patil
Product  : Wireless Keyboard
Price    : ₹1,499.50
Quantity : 2
----------------------------------------
Total    : ₹2,999.00
========================================

Project Enhancements

  • Accept customer details using input().
  • Validate quantity and price before performing calculations.
  • Display multiple products in aligned rows.
  • Add discounts and tax calculations.
  • Save the invoice to a text file.
  • Use a suitable locale-aware formatting approach if the invoice must follow a specific currency convention.

26. Practice Exercises

  1. Write a program that converts a sentence to uppercase, lowercase, and title case.
  2. Remove leading and trailing spaces from a user-entered name.
  3. Count how many times the word Python appears in a sentence.
  4. Replace every occurrence of old with new in a given string.
  5. Split a comma-separated list of names and print each name on a separate line.
  6. Join a list of words using a hyphen as the separator.
  7. Check whether a string contains only alphabetic characters or only digits.
  8. Format a floating-point price to two decimal places.
  9. Display a number with comma separators and align it within a fixed-width column.
  10. Create a student report showing the student's name, subject, marks, and percentage.
  11. Build a simple text-cleaning program that trims spaces and normalizes text case.
  12. Create a product invoice with multiple items, quantities, prices, and a final total.

27. Interview Questions and Answers

Q1. What is a string in Python?

A string is an immutable sequence of Unicode characters used to represent text.

Q2. What is the difference between upper() and lower()?

upper() returns a string with cased characters converted to uppercase, while lower() returns a lowercase version.

Q3. What is the difference between find() and index()?

Both search for a substring. find() returns -1 when the substring is absent, while index() raises ValueError.

Q4. What does strip() do?

It removes whitespace or specified characters from both ends of a string. It does not remove those characters from the middle.

Q5. What is the difference between split() and join()?

split() divides a string into a list of substrings. join() combines strings from an iterable into one string using a separator.

Q6. Why are strings immutable?

String immutability means a string's characters cannot be changed in place. Operations that appear to modify text return a new string, helping make string values predictable and safe to share.

Q7. What is an f-string?

An f-string is a formatted string literal that evaluates expressions inside curly braces, making it convenient to combine text and values.

Q8. How can you display two decimal places?

Use a format specification such as f"{price:.2f}".

Q9. What is the difference between isdigit(), isdecimal(), and isnumeric()?

They test different Unicode character categories. isdecimal() is the narrowest, isdigit() accepts additional digit characters, and isnumeric() accepts an even broader range of numeric characters. Their results may differ for certain Unicode characters.

Q10. How do you replace a substring in Python?

Use replace(old, new). You can provide an optional count to limit the number of replacements.

Q11. Does replace() modify the original string?

No. Strings are immutable, so replace() returns a new string. Assign the returned result if you need to retain it.

Q12. What is the difference between f-strings and str.format()?

Both support formatted output. F-strings place expressions directly inside the string literal, while str.format() supplies values through a method call and placeholders.

Q13. How do you format a number with thousands separators?

Use a format specifier such as f"{amount:,}" or "{:,.2f}".format(amount).

Q14. How can you check whether a string starts with a specific prefix?

Use startswith(). For example, "report.pdf".startswith("report") returns True.

Q15. How can string methods help in data cleaning?

Methods such as strip(), replace(), lower(), split(), and join() help remove unwanted surrounding whitespace, standardize text, replace known values, and transform text into useful structures.

28. Quick Revision Checklist

  • Understand string creation, indexing, immutability, and iteration.
  • Know case conversion methods such as upper(), lower(), title(), and casefold().
  • Use strip(), lstrip(), and rstrip() to clean text boundaries.
  • Search for text using find(), index(), and count().
  • Check prefixes and suffixes with startswith() and endswith().
  • Replace substrings with replace().
  • Separate text with split() and combine strings with join().
  • Validate basic character categories with methods such as isalpha() and isdigit().
  • Align text with center(), ljust(), and rjust().
  • Use f-strings for clear formatting of variables, numbers, percentages, and tables.
  • Understand positional and named placeholders in str.format().
  • Recognize percent-style formatting in older Python code.
  • Practice creating reports and invoices using real-world data.

29. Conclusion

String methods and formatting are essential parts of Python programming. String methods help developers clean, search, validate, replace, split, and combine text, while formatting tools help present information in a readable and consistent way.

For most new Python code, f-strings are an excellent default for readable output. Combine them with appropriate string methods, careful input validation, and clear variable naming to build reliable applications, reports, invoices, and data-processing programs.

Continue learning through the JustAcademy Python Training Course, explore the course demo registration page, or visit the JustAcademy website.

whatsapp